/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package locusts.server.collisions;

import locusts.common.entities.CropsEntity;
import locusts.common.entities.Entity;
import locusts.common.entities.EntityData;
import locusts.common.entities.EntityDataList;

/**
 *
 * @author Hamish Morgan
 */
public class GrowShrinkCropPile implements CollisionResponce {

    private final EntityDataList data;

    public GrowShrinkCropPile(EntityDataList data) {
        this.data = data;
    }

    public void doCollision(Collidable a, Collidable b, double period) {
        Entity pile = null;
        boolean grow = true;
        if (a instanceof CollidableEntityAdapter) {
            pile = ((CollidableEntityAdapter) a).getEntity();
        } else if (a instanceof CropsEntity) {
            if (!((CropsEntity) a).isPickingUp())
                grow = false;
            pile = ((CropsEntity) a);

        } else {
            throw new IllegalArgumentException(
                    "The Collidable arguments to not represent known entities.");
        }
        Entity farm = null;
        if (b instanceof CollidableEntityAdapter) {
            farm = ((CollidableEntityAdapter) b).getEntity();
        } else if (b instanceof Entity) {
            farm = ((Entity) b);
        } else {
            throw new IllegalArgumentException(
                    "The Collidable arguments to not represent known entities.");
        }

        EntityData farmD = data.get(farm);
        EntityData pileD = data.get(pile);

        if (grow) {
//            double delta = Math.min(pileD.getMaxEnergy() - pile.getEnergy(), farm.getEnergy()) * .1;
//            delta = Math.max(1, delta);
            double delta = 8;
            delta = Math.min(delta, farm.getEnergy() - farmD.getMinEnergy());
            delta = Math.min(delta, pileD.getMaxEnergy() - pile.getEnergy());
//            System.out.println(delta);

            if(delta > 0) {
                farm.setEnergy(farm.getEnergy() - delta);
                pile.setEnergy(pile.getEnergy() + delta);
                farm.setModified();
                pile.setModified();
            }
        } else {
//            double delta = Math.min(farmD.getMaxEnergy() - farm.getEnergy(), pile.getEnergy()) * .1;
//            delta = Math.max(1, delta);
            double delta = 8;
//            double delta = Math.max(1, pile.getEnergy() * .1);
            
            delta = Math.min(delta, pile.getEnergy() - pileD.getMinEnergy());
            delta = Math.min(delta, farmD.getMaxEnergy() - farm.getEnergy());
//            System.out.println(delta);

            if(delta > 0) {
                farm.setEnergy(farm.getEnergy() + delta);
                pile.setEnergy(pile.getEnergy() - delta);
                farm.setModified();
                pile.setModified();
            }

        }


    }
}
